package com.erdos.upc.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;

import com.erdos.cas.client.MesHttpClient;
import com.erdos.common.web.BaseAction;
import com.erdos.core.service.ReferenceService;
import com.erdos.upc.core.UpcConst;
import com.erdos.upc.core.UpcUser;
import com.erdos.upc.core.UpcUtil;
import com.erdos.upc.encode.PasswordEncode;
import com.erdos.upc.entity.MenuVO;
import com.erdos.upc.entity.User;
import com.erdos.upc.service.AuthService;
import com.erdos.upc.service.GroupService;
import com.erdos.upc.service.UserService;
import com.opensymphony.xwork2.ActionContext;


public class AuthAction extends BaseAction<User> {
	
	private static final long serialVersionUID = 7119473154777653647L;
	
	private static final Log logger = LogFactory.getLog(AuthAction.class);
	/**
	 * 旧密码
	 */
	private String oldPwd;
	/**
	 * 新密码
	 */
	private String newPwd;
	/**
	 *  员工号
	 */
	private String resetPin;
	/**
	 * 重设密码
	 */
	private String resetPwd;
	/**
	 *  确认密码
	 */
	
	/*
	 * 用户组
	 */
	private String authUserGroup;
	
	//班次
	private String authUserShift;
	private String shift;
	private String teamTime;
	
	private String confirmPwd;

	private UserService userService;
	
	private GroupService groupService;

	private PasswordEncode passwordEncode;

	private AuthService authService;
	
	private ReferenceService referenceService;
	
	public String getOldPwd() {
		return oldPwd;
	}

	public void setOldPwd(String oldPwd) {
		this.oldPwd = oldPwd;
	}

	public String getNewPwd() {
		return newPwd;
	}

	public void setNewPwd(String newPwd) {
		this.newPwd = newPwd;
	}

	public String getConfirmPwd() {
		return confirmPwd;
	}

	public void setConfirmPwd(String confirmPwd) {
		this.confirmPwd = confirmPwd;
	}

	public String getResetPin() {
		return resetPin;
	}

	public void setResetPin(String resetPin) {
		this.resetPin = resetPin;
	}

	public String getResetPwd() {
		return resetPwd;
	}

	public void setResetPwd(String resetPwd) {
		this.resetPwd = resetPwd;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public void setPasswordEncode(PasswordEncode passwordEncode) {
		this.passwordEncode = passwordEncode;
	}

	public void setAuthService(AuthService authService) {
		this.authService = authService;
	}
	
	public String init()
	{
		HttpServletRequest request = ServletActionContext.getRequest();
		request.setAttribute("authLoginId","test");

		return SUCCESS;
	}
	
	/**
	 * 登录
	 * @return
	 */
	public String login() {
		logger.debug("do login auth");
		Map<String, Object> params = new HashMap<String, Object>();
		HttpServletRequest request = ServletActionContext.getRequest();
		String ssoLoginId = request.getParameter("loginId");
		logger.debug("ssoLoginId:" + ssoLoginId);
		String ssoToken = request.getParameter("token");
		logger.debug("ssoToken:" + ssoToken);
		if (StringUtils.isEmpty(ssoLoginId) || StringUtils.isEmpty(ssoToken)) {
			String authLoginId = request.getParameter("authLoginId");
			String authLoginPasswd = request.getParameter("authLoginPasswd");
			//String authUserGroupValue = request.getParameter("authUserGroup");
			//String authUserShiftValue = request.getParameter("authUserShift");
			//authU/serGroup = authUserGroupValue;
			//authUserShift = authUserShiftValue;
			if (StringUtils.isEmpty(authLoginId)
					|| StringUtils.isEmpty(authLoginPasswd)) {
				return INPUT;
			}
			String realPassword = authLoginPasswd;
			if (passwordEncode != null) {
				realPassword = passwordEncode.encode(authLoginPasswd);
			}
			params.put("pin", authLoginId);
			params.put("password", realPassword);
			//params.put("userGroup", authUserGroupValue);
		} else {
			MesHttpClient mesHttpClient = new MesHttpClient();
			boolean pass = mesHttpClient.checkToken(ssoLoginId, ssoToken);
			if(!pass) {
				logger.debug("SSO authorization failed.");
				this.addActionError(getText("sso.auth.denied"));
				return INPUT;
			}
			params.put("pin", ssoLoginId);
		}
		//User user = userService.findUserByUserNameUserGP(params);
		User user = userService.findUniqueByParams(params);
		
		HttpSession session = request.getSession();
		if (user != null) {
			logger.debug("set auth info for user:" + user.getPin());
			Map<String,Object> extParams=new HashMap<String,Object>();
			extParams.put("loginIp", request.getRemoteAddr());
			user.setLoginGroup(authUserGroup);
			UpcUser upcUser = authService.authUpcUser(extParams, user);
			
			upcUser.setLoginShift(authUserShift);			
			session.setAttribute(UpcConst.LOGIN_UPC_USER, upcUser);
			
			UpcUtil.setUpcUserVO(user.getPin(), authUserGroup,shift,teamTime,upcUser.getFacilityIds(),upcUser.getFacilityNo());
			logger.debug(UpcUtil.getUpcUserPin()
					+ " put to threadlocal success");
			logger.debug("login successful.");
			logger.debug("context locale:"+ActionContext.getContext().getLocale());
			logger.debug("session locale:"+session.getAttribute("WW_TRANS_I18N_LOCALE"));
			return SUCCESS;
		} else {
			logger.debug("login.auth.denied");
			request.setAttribute("authError", getText("login.auth.denied"));
			this.addActionError(getText("login.auth.denied"));
			return INPUT;
		}
	}

	/**
	 * 登出
	 * @return
	 */
	public String logout() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		UpcUser loginUser = UpcUtil.getUpcUser(request);
		if (logger.isDebugEnabled()) {
			if (loginUser == null) {
				logger.debug("[N/A] is logout...");
			} else {
				logger.debug("[" + loginUser.getLoginId() + "] is logout...");
			}
		}
		session.invalidate();
		return SUCCESS;
	}

	/**
	 * menu
	 */
	public String menu() {
		logger.debug("menu test start");
		HttpServletRequest request = ServletActionContext.getRequest();
		UpcUser loginUser = UpcUtil.getUpcUser(request);
//		loginUser = new UpcUser();
//		Privilege p = new Privilege();
//		p.setCode("0101");
//		loginUser.getPrivileges().add(p);
		List<MenuVO> menus = authService.authUserMenu(loginUser);
		request.setAttribute("menus", menus);
		return SUCCESS;
	}

	/**
	 * 显示用户自助修改密码页面
	 */
	public String changePasswdDisplay() {
		return INPUT;
	}

	/**
	 * 显示管理员修改密码页面
	 */
	public String adminChangePasswdDisplay() {
		return INPUT;
	}

	/**
	 * 用户自助修改密码
	 */
	public String changePasswd() {
		UpcUser upcUser = UpcUtil.getUpcUser(this.getRequest());
		String pin = upcUser.getLoginId();
		authService.changePasswd(pin, newPwd);
		this.getRequest().setAttribute("method", "updatePasswd");
		saveBizMessage(getText("tips.updatePasswd.success",
				new String[] { String.valueOf(entity.getSid()) }));
		return SUCCESS;
	}

	/**
	 * 用户自助修改密码
	 */
	public String adminChangePassword() {
		logger.debug("admin resetPin:"+resetPin);
		logger.debug("resetPwd:"+resetPwd);
		authService.changePasswd(resetPin, resetPwd);
		this.getRequest().setAttribute("method", "updatePasswd");
		saveBizMessage(getText("tips.updatePasswd.success",
				new String[] { String.valueOf(entity.getSid()) }));
		return SUCCESS;
	}

	/**
	 * changePasswd校验
	 */
	public void validateChangePasswd() {
		logger.debug("validate Change Passwd start!");
		if (StringUtils.isNotEmpty(oldPwd)) {
			UpcUser upcUser = UpcUtil.getUpcUser(this.getRequest());
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("pin", upcUser.getLoginId());
			User user = userService.findUniqueByParams(params);
			if (!passwordEncode.encode(oldPwd).equals(user.getPassword())) {
				addFieldError("oldPwd", getText("validation.exist.passwd"));
			}
		}
	}


	public GroupService getGroupService() {
		return groupService;
	}

	public ReferenceService getReferenceService() {
		return referenceService;
	}

	public void setReferenceService(ReferenceService referenceService) {
		this.referenceService = referenceService;
	}

	public void setGroupService(GroupService groupService) {
		this.groupService = groupService;
	}

	public String getAuthUserGroup() {
		return authUserGroup;
	}

	public void setAuthUserGroup(String authUserGroup) {
		this.authUserGroup = authUserGroup;
	}
}
